package cs304.p3.library.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import cs304.p3.library.framework.IoC;
import cs304.p3.library.framework.LibraryDataAccessContext;
import cs304.p3.library.model.LoginForm;

public class LoginController extends Controller {
	
	private LoginForm loginForm = new LoginForm();

	public void login(){

		//write user name to local file
		saveUserName();

		LibraryDataAccessContext.jdbcUrl = loginForm.getJdbcUrl();
		LibraryDataAccessContext.username = loginForm.getUsername();
		LibraryDataAccessContext.password = loginForm.getPassword();
		
		IoC.switchConnection(LibraryDataAccessContext.reconnect());
		
		loginForm.setUsername(LibraryDataAccessContext.username);
		loginForm.setPassword(LibraryDataAccessContext.password);
		loginForm.setJdbcUrl(LibraryDataAccessContext.jdbcUrl);
	}

	public void saveUserName() {
		boolean checked = loginForm.isRememberUsername();

		Properties properties = new Properties();
		OutputStream outputStream = null;
		File file = new File("application.properties");
		try{
			if(!file.exists()) file.createNewFile();
			outputStream = new FileOutputStream(file);
		}catch(IOException e){
			System.err.println("Error while creating properties files");
			e.printStackTrace();
		}

		if(checked) properties.setProperty("username", loginForm.getUsername());
		properties.setProperty("checked", String.valueOf(checked));

		//Write out
		try {
			properties.store(outputStream, "");
			outputStream.flush();
			outputStream.close();
		} catch (IOException e){ e.printStackTrace(); }
	}
	
	public void readUserName(){
		Properties properties = new Properties();
		InputStream inputStream = null;
		File file = new File("application.properties");
		try{
			if(!file.exists()) file.createNewFile();
			inputStream = new FileInputStream(file);
			properties.load(inputStream);
			boolean checked = Boolean.parseBoolean(properties.getProperty("checked"));
			if(checked){
				loginForm.setRememberUsername(true);
				loginForm.setRememberedUserName(properties.getProperty("username"));
			}
			inputStream.close();
		}catch(IOException e){
			System.err.println("Error while creating properties files");
			e.printStackTrace();
		}
	}

//	public void setLoginForm(LoginForm loginForm) {
//		this.loginForm = loginForm;
//	}

	public LoginForm getLoginForm() {
		return loginForm;
	}

	@Override
	public void cleanUp() {
		loginForm = new LoginForm();
	}
}
